<?php
/**
 * This script simply checks your messages folder and uses googles translation engine to auto translate your application
 * say for example your main translation file is is english at /messages/EN/App.php and you want spanish 
 * the contents will be translated using googles engine and placed into /messages/SP/App.php, the more files you add 
 * to your main lang, the more will be translated its automatic
 * you also have the ability to allow the files to be overwritten or not, 
 * 
 * TODO: verbose method should be added too, to check all diferences in a line by line  confirm change[y/n]:  matter .
 */
 
class AutoTranslateCommand extends CConsoleCommand
{
    const  key='AIzaSyBD-qVOiRrYo5wtd34IDKTgW7v0Gx7ngUc';
    public $format='text';
    public $prettyprint=false;
    public $baselang='EN';
    public static $readonly=false;
    public $languagelist=array();
    public $translationtype='phrase';
    protected $toTranslate=array();
    
    public function run($args)
    {
	    $args = count($args) > 0 ? $args : array();
	    $folders = glob( Yii::getPathOfAlias('application.messages') . DIRECTORY_SEPARATOR . '*');
	    $filelist=array();
	    $translated=array();
	    
		if(count($folders)<1) 
		{
		throw new CException('Have you created a translation file?');
		}else if(count($folders)>1)
		{
		self::e('Select your primary language.');
		    foreach($folders as $k=>$folder)
		    {
		    self::e("[$k] : $folder");
		    }
		$selected_language = trim(fgets(STDIN));
		

		while(!array_key_exists($selected_language,$folders))
		{
		   self::e('Select your primary language.');
		    foreach($folders as $k=>$folder)
		    {
		    self::e("[$k] : $folder");
		    } 
		    $selected_language = trim(fgets(STDIN));
		} // this will be the # in the array

		//var_dump($folders);
		self::e("The base language to be used is $folders[$selected_language]");
		self::e('overwrite other language files    [y/n]');
		$readonly=trim(fgets(STDIN));
		if (strtolower($readonly) == 'y')
		{
		    self::$readonly=true;
		} 
		$filelist=glob($folders[$selected_language] . DIRECTORY_SEPARATOR . '*.php');
		$this->baselang=basename($folders[$selected_language]);
		}else{
		$filelist=glob($folders[0] . DIRECTORY_SEPARATOR . '*.php');
		$this->baselang=basename($folders[0]);
		}
		//var_dump($this->baselang);
		
	    //loop through each file in list
	    self::loadgooglelangs();
	    $this->languagelist=array('yi');
	    
	foreach($this->languagelist as $lang)
	{
	    foreach($filelist as $file)
	    {
		$this->toTranslate[$file]=$this->fileToTranslate($file,$lang);
		
	    }
	    
	     foreach($filelist as $file)
	    {
	    $translated[$file]=$this->translate($file,$this->toTranslate);
	    }
	    
	}
	//var_dump($translated);
	//var_dump($this->toTranslate);
	//var_dump($translated);
    }
	
	/*
	 * string @args
	 * This function outputs text to the console window
	*/
	public static function e($msg='')
    {
        $msg = preg_replace('@\bln(\d+)\b@e', 'str_repeat("\n", \\1)', $msg);
        echo "$msg\n";
    }
    
    public function fileToTranslate($file,$lang)
    {
	//$escapedtext=array();
		//load the array of translations
		$to_translate=self::loadtranslation($file);
		//var_dump($to_translate);
	    //loop through array sending the translatable words to google for translation
		    foreach($to_translate as $tkey=>$basestring)
		    {
			$escapedtext[$tkey]=array();
			//$escaped_array=array();
		    
				preg_match_all( "%\".*?\"|\{.*?\}%", $basestring , $delimeter_location);
				echo 'key is ['.$tkey."]\n";
				    if(isset($delimeter_location[0][0]))
					{
					foreach($delimeter_location[0] as $dindex)
					    {
						echo ' text to escape is "'. $dindex .'"'."\n";
					//	array_push($escaped_array,"/$dindex/");
						array_push($escapedtext[$tkey],"$dindex");
					    }
					}
	    
				//unset($escaped_array);
				
	    // $translated[$tkey]=self::googletranslate($escaped_string,$lang,$this->baselang); 
		    } 
	     
	    /*
	    TODO:: check if file exists and overwrite is true 
	    write that array to a new file in the correct lang dir
	    */
	     return $escapedtext;
	    
    }
    
     /*
    * string @args = q(query), t(target lang),s(source lang)
    * return array()
    * This function loads the translation
    */  
    public static function translate($file,$escaped_array=array())
    {
	
	 // var_dump($escaped_array);
	   //parse out "{*}" and {*} store position in array
	   $to_translate=self::loadtranslation($file);
	foreach($escaped_array as $key=>$value)
	{
	    var_dump($value);
/*
	$escaped_string=preg_replace( $escaped_array, '{}',$basestring);
	$escaped_string=str_replace(' ','%20',$escaped_string);
	echo "text sent to google  is \"$escaped_string\" \n";
	 //var_dump($earray);
	    foreach(escaped_array as $tkey=>$tvalue)
	    {
	    //var_dump($delimeter_location);
	    //store in an new translated array
	$translated[$tkey]=self::googletranslate($escaped_string,$lang,$this->baselang);
	$translated_array[$tkey]=$translated[$tkey]->data->translations[0]->translatedText;
*/
	    }
	}
	   // return $translated_array;
	    //
  //  }
    
     /*
    * string @args = q(query), t(target lang),s(source lang)
    * return array()
    * This function loads the translation
    */  
     public static function googletranslate($q,$t,$s="en") 
    {
        $url='https://www.googleapis.com/language/translate/v2?key='.self::key.'&source='.$s.'&target='.$t .'&q='.$q;
	$json=file_get_contents($url);
	//var_dump($url);
	$new_word=json_decode($json);
	return $new_word;
    }

    /*
    * string @args
    * return array()
    * This function loads the translation
    */    
    public static function loadtranslation($translation)
    {
	$array=include($translation);
	return $array;
    }
    
    public function loadgooglelangs()
    {
    $langs=array(
	'Afrikaans'=>'af',
	'Albanian'=>'sq',
	'Arabic'=>'ar',
	'Basque'=>'eu',
	'Belarusian'=>'be',
	'Bulgarian'=>'bg',
	'Catalan'=>'ca',
	'Chinese Simplified'=>'zh-CN',
	'Chinese Traditional'=>'zh-TW',
	'Croatian'=>'hr',
	'Czech'=>'cs',
	'Danish'=>'da',
	'Dutch '=>'nl',
	'English'=>'en',
	'Estonian'=>'et',
	'Filipino'=>'tl',
	'Finnish'=>'fi',
	'French'=>'fr',
	'Galician'=>'gl',
	'German'=>'de',
	'Greek'=>'el',
	'Haitian Creole'=>'ht',
	'Hebrew'=>'iw',
	'Hindi'=>'hi',
	'Hungarian'=>'hu',
	'Icelandic'=>'is',
	'Indonesian'=>'id',
	'Irish'=>'ga',
	'Italian'=>'it',
	'Japanese'=>'ja',
	'Latvian'=>'lv',
	'Lithuanian'=>'lt',
	'Macedonian'=>'mk',
	'Malay'=>'ms',
	'Maltese'=>'mt',
	'Norwegian'=>'no',
	'Persian'=>'fa',
	'Polish'=>'pl',
	'Portuguese'=>'pt',
	'Romanian'=>'ro',
	'Russian'=>'ru',
	'Serbian'=>'sr',
	'Slovak'=>'sk',
	'Slovenian'=>'sl',
	'Spanish'=>'es',
	'Swahili'=>'sw',
	'Swedish'=>'sv',
	'Thai'=>'th',
	'Turkish'=>'tr',
	'Ukrainian'=>'uk',
	'Vietnamese'=>'vi',
	'Welsh'=>'cy',
	'Yiddish'=>'yi',
	);
    $this->languagelist=$langs;
    }
}

?>
